Named Tasks
Piscina supports running named tasks within a single worker file. This example demonstrates how to use a dispatcher pattern to execute different operations based on the task name.
- Javascript
- Typescript
index.js
'use strict';
const Piscina = require('piscina');
const { resolve } = require('path');
const { makeTask } = require('./helper');
const piscina = new Piscina({
filename: resolve(__dirname, 'worker.js')
});
(async function () {
const result = await Promise.all([
piscina.run(makeTask('add', 4, 6)),
piscina.run(makeTask('sub', 4, 6))
]);
console.log(result);
})();
index.ts
import Piscina from "piscina";
import { resolve } from "path";
import { filename } from "./worker";
import { makeTask } from "./helper";
const piscina = new Piscina({
filename: resolve(__dirname, "./workerWrapper.js"),
workerData: { fullpath: filename },
});
(async function () {
const result = await Promise.all([
piscina.run(makeTask('add', 4, 6)),
piscina.run(makeTask('sub', 4, 6))
]);
console.log(result);
})();
The worker file uses a dispatcher to handle different operations:
- Javascript
- Typescript
worker.js
'use strict';
const { dispatcher } = require('./helper');
module.exports = dispatcher({
add (a, b) { return a + b; },
sub (a, b) { return a - b; }
});
worker.ts
import { dispatcher } from './helper';
export default dispatcher({
add (a: number, b: number): number { return a + b; },
sub (a: number, b: number): number { return a - b; }
});
The helper file provides utility functions for creating tasks and dispatching them:
- Javascript
- Typescript
helper.js
function makeTask (op, ...args) {
return { op, args };
}
function dispatcher (obj) {
return async ({ op, args }) => {
return await obj[op](...args);
};
}
module.exports = {
dispatcher,
makeTask
};
helper.ts
type Task = {
op: string;
args: any[];
};
export function makeTask (op: string, ...args: any[]): Task {
return { op, args };
}
export function dispatcher (obj: Record<string, Function>) {
return async ({ op, args }: Task) => {
return await obj[op](...args);
};
}
You can also check out this example on github.